<template>
  <div >
    <div class="head-sculpture">
      <el-row class="demo-avatar demo-basic">
        <el-col :span="5"  >
          <el-upload
              class="avatar-uploader"
              action="/api/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-col>
        <el-col :span="3">
          <div class="userinfoName">
            <el-row >
              {{user.account}}
              <input class="jianming"
                     placeholder="编辑我的个人签名"
                     v-model="input"
                     size="mini"
                     clearable>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </div>

    <div>
      <el-tabs v-model="activeName"  class="table-bottom"  stretch>
        <el-tab-pane label="用户管理" name="first">
          <div class="first-row" style="background-color: transparent;">
            <!-- 第一行 -->
            <el-descriptions title="用户信息" :column="3" border style="margin-left: 20px;margin-right: 20px" content-class-name="description">
              <el-descriptions-item label="姓名" style="background-color: transparent!important;">{{ user.name }}</el-descriptions-item>
              <el-descriptions-item v-if="user.role === 1 || user.role === 2" label="年龄">{{ user.age }}</el-descriptions-item>
              <el-descriptions-item label="账号">{{ user.account }}</el-descriptions-item>
              <el-descriptions-item label="密码">{{ user.passwd }}</el-descriptions-item>
              <el-descriptions-item label="手机号">{{ user.phone }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ user.email }}</el-descriptions-item>
              <el-descriptions-item label="角色">
                <el-tag
                    type="success"
                    size="small"
                    effect="plain">
                {{ getRoleName(user.role) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="城市">{{ user.city }}</el-descriptions-item>
              <el-descriptions-item label="省份">{{ user.province }}</el-descriptions-item>
              <el-descriptions-item v-if="user.role === 1 || user.role === 2" label="学校名称">{{ user.schoolName }}</el-descriptions-item>
              <template v-slot:extra>
                <el-button @click="showDialog=true" round>修改</el-button>

              <el-dialog :visible.sync="showDialog " title="编辑用户信息" style="width: 1200px;margin-left: 200px">
                <el-form :model="userUpdate" label-width="100px" style="width: 500px">
                  <!-- 用户信息编辑表单 -->
                  <el-form-item label="姓名" >
                    <el-input v-model="userUpdate.name"></el-input>
                  </el-form-item>
                  <el-form-item label="密码">
                    <el-input v-model="userUpdate.passwd"></el-input>
                  </el-form-item>
                  <el-form-item label="手机号">
                    <el-input v-model="userUpdate.phone"></el-input>
                  </el-form-item>
                  <el-form-item label="邮箱">
                    <el-input v-model="userUpdate.email"></el-input>
                  </el-form-item>
                  <el-form-item label="省份">
                    <el-input v-model="userUpdate.province"></el-input>
                  </el-form-item>
                  <el-form-item label="城市">
                    <el-input v-model="userUpdate.city"></el-input>
                  </el-form-item>

                  <!-- 其他用户信息字段 -->

                  <!-- 保存按钮 -->
                  <el-button type="primary" @click="saveUser">保存</el-button>
                </el-form>
              </el-dialog>
              </template>
            </el-descriptions>
          </div>
        </el-tab-pane>
        <el-tab-pane label="数据统计" name="second" v-if="this.userRole===1||this.userRole===2">
          <el-row>
            <el-col :span="12">
              <el-card class="statistics-card" style="width: 600px">
                <div slot="header" style="font-family: 'Arial', sans-serif;font-weight: 700;font-size: 20px">
                  活动统计
                </div>
                <div id="statistics" style="width: 600px; height: 400px; background-color: transparent;"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="statistics-card" style="width: 600px">
                <div slot="header" style="font-family: 'Arial', sans-serif;font-weight: 700;font-size: 20px">
                  活动统计
                </div>
                <div id="statistics2" style="width: 600px; height: 400px;margin-top: -50px; background-color: transparent;"></div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="我的收藏">
          <el-row>
            <el-col :span="12" v-for="(activity, index) in collectActivities" :key="index">
              <el-card style="margin-bottom: 20px; width: 600px; height: 400px; margin-left: 20px; margin-right: 20px;
                box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);background-color: #f5f7fa;position: relative;">
                <div slot="header" class="clearfix">
                  <span style="font-size: 25px;font-weight: bold;">活动{{ index + 1 }}</span>
                </div>
                <div class="activity-content">
                  <div class="image-wrapper">
                    <img v-if="activity.url && activity.url[0].url" :src="activity.url[0].url" alt="活动图片" style="max-width: 40%;
                     height: auto;" />
                  </div>
                  <div class="details-wrapper" style="position: absolute; top: 60px; left: 250px;">
                    <p style="font-size: 20px;font-weight: bold;">活动详情：</p>
                    <div v-html="activity.activityDescription"></div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import {getUserByAccount, saveUserUrl, selectUserUrl, updateUser} from '../../../../api/user'
import * as echarts from 'echarts'
import {getActivityByUid, getDetail} from '../../../../api/activity'
import {getCollection} from '../../../../api/collect'
import {getActivityUrl} from '../../../../api/activityUrl'
import {downloadFile} from '../../../../api/api'
export default {
  name: 'user',
  inject: ['reload'],
  computed: {
    ...mapGetters({
      userRole: 'user/getUserRole',
      userAccount: 'user/getUserAccount',
      userId: 'user/getUserId'
    })
  },
  methods: {
    saveUser () {
      console.log(this.userUpdate)
      // 调用更新用户信息的方法，并将更新后的用户信息传递给 updateUser()
      updateUser(this.userUpdate).then(result => {
        // 更新成功后执行的操作
        this.reload() // 重新加载数据
        this.showDialog = false // 关闭弹窗
      }).catch(error => {
        // 处理更新失败的情况
        console.error('更新用户信息出错：', error)
      })
    },
    // 在 getCollection 中传递 aid 给 showDetail
    getCollection () {
      getCollection(this.userId).then(result => {
        this.collection = result
        // 更新 activities 中的 detail 和 imgUrlActivity
        this.collection.forEach(activity => {
          getDetail(activity.aid).then(result1 => {
            getActivityUrl(activity.aid).then(result2 => {
              const activityUpdate = result1
              activityUpdate.url = result2
              this.collectActivities.push(activityUpdate)
            })
          }
          )
        })
      })
    },
    downloadFile () {
      getActivityUrl(this.activityId).then(urlResult => {
        let obj = {
          path: urlResult[0].url
        }
        downloadFile(obj)
          .then(response => {
            // 通过创建 Blob 对象来处理下载的文件
            const blob = new Blob([response], { type: 'image/jpeg' })

            // 创建一个 URL，用于文件下载
            const downloadUrl = window.URL.createObjectURL(blob)

            // 创建一个 <a> 标签来触发下载
            const link = document.createElement('a')
            link.href = downloadUrl
            link.download = decodeURIComponent(urlResult[0].fileName)
            link.style.display = 'none'

            document.body.appendChild(link)
            link.click()

            // 清理资源
            window.URL.revokeObjectURL(downloadUrl)
            document.body.removeChild(link)
          })
          .catch(error => {
            console.error(error)
            // 处理错误
          })
      })
    },
    async getActivityByUid () {
      if (this.userRole === 1 || this.userRole === 2) {
        try {
          const result = await getActivityByUid(this.userId)
          this.activities = result
          this.initDiv() // 在获取到活动列表数据后调用 initDiv()
          this.initDiv2()
        } catch (error) {
          console.error('未获取到活动:', error)
        }
      } else {
      }
    },
    initDiv () {
      let obj = echarts.init(document.getElementById('statistics'))
      console.log(this.activities)
      // 统计不同类型活动的数量
      let activityTypes = {
        1: 0, // 线上
        2: 0, // 校内
        3: 0 // 校外
      }
      // 统计每种类型活动的数量
      this.activities.forEach(activity => {
        if (activity.type === 1) {
          activityTypes[1]++
        } else if (activity.type === 2) {
          activityTypes[2]++
        } else if (activity.type === 3) {
          activityTypes[3]++
        }
      })

      // 使用统计的数据更新饼状图的内容
      let option = {
        title: {
          text: '参与活动的比例',
          subtext: '我的活动',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: [
              { value: activityTypes[1], name: '线上' }, // type为1的是线上
              { value: activityTypes[2], name: '校内' }, // type为2的是校内
              { value: activityTypes[3], name: '校外' } // type为3的是校外
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      obj.setOption(option)
    },
    initDiv2 () {
      let obj = echarts.init(document.getElementById('statistics2'))

      // 静态数据，模拟活动数量
      let activityData = [10, 20, 15, 30, 25, 35, 40]

      // 使用静态数据设置横轴时间
      let timeData = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul']

      let option = {
        title: {
          text: '参加活动数量', // 标题为“参加活动数量”
          left: 'center' // 居中显示
        },
        xAxis: {
          type: 'category',
          data: timeData,
          axisLabel: {
            interval: 0, // 横轴间隔设置为0，显示全部
            rotate: 45 // 横轴标签旋转45度方便展示
          }
        },
        yAxis: {
          type: 'value',
          min: 0, // 竖轴最小值
          max: 50, // 竖轴最大值
          interval: 5 // 竖轴间隔为5
        },
        series: [
          {
            data: activityData,
            type: 'line'
          }
        ]
      }

      obj.setOption(option)
    },
    saveImageUrlToDatabase () {
      saveUserUrl(this.userId, this.imageUrl)
        .then(response => {
          // 如果需要，处理成功的响应
          console.log('图片URL已保存到数据库')
        })
        .catch(error => {
          // 处理无法保存图片URL的错误
          console.error('保存图片URL时出错:', error)
        })
    },

    getRoleName (role) {
      if (role === 1) {
        return '学生'
      } else if (role === 2) {
        return '老师'
      } else if (role === 3) {
        return '学院'
      } else if (role === 4) {
        return '学校'
      } else {
        return '其他'
      }
    },
    // 头像上传
    handleAvatarSuccess (res, file) {
      // response是服务器返回的上传成功的结果
      console.log('上传成功:', res)
      // 可以将服务器返回的信息保存到组件的数据中
      this.imageUrl = res.url
      this.saveImageUrlToDatabase()
    },
    getAvatar () {
      selectUserUrl(this.userId).then(result => {
        if (result === '' || result === null) {
        } else {
          this.imageUrl = result
        }
      })
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 获取信息
    async fetchUser () {
      try {
        const accountNumber = this.userAccount
        const userData = await getUserByAccount(accountNumber)

        this.user = userData
        this.getAvatar()
        this.userUpdate = this.user
        await this.getActivityByUid()
      } catch (error) {
        console.error('Error fetching user or activity data:', error)
      }
    }
    // 下部
    // 用户信息
  },
  mounted () {
    this.fetchUser()
    this.getCollection()
  },
  data () {
    return {
      showDialog: false,
      userUpdate: {},
      collectActivities: [],
      imageUrlActivity: '', // 图片 URL
      detail: '', // 活动详情
      collection: [], // 存储收藏活动的数组
      activities: [], // 存储活动列表的数组
      input: '', // 输入框的内容
      like: true, // 布尔值
      imageUrl: '', // 用户头像的 URL
      user: {}, // 用户信息对象
      circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png', // 圆形图片的 URL
      activeName: 'first' // 当前激活的标签名
      // 其他可能的属性...
    }
  }
}
</script>
<style scoped>
.activity-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.image-wrapper {
  flex: 1;
  margin-right: 20px; /* 调整图片与文字之间的间距 */
}

.details-wrapper {
  flex: 2;
}

.statistics-card .el-card__header {
  font-family: 'Arial', sans-serif;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.statistics-card {
  margin-top: -10px;
  margin-left: 20px;
  width: calc(50% - 40px); /* 宽度为父容器宽度减去两边 margin 的宽度 */
  height: 400px;
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
  background-color: #f5f7fa;
  color: #495060;
}
/* 统计图表样式 */
#statistics {
  width: 100%;
  height: 100%;
  background-color: transparent;
}

/* 将 el-description 组件的背景色设置为透明 */
/deep/ .el-descriptions {
  background-color: transparent;
}

/*最外层透明*/
/deep/ .el-table, /deep/ .el-table__expanded-cell{
  background-color: transparent;
}
/* 表格内背景颜色 */
/deep/ .el-table th,
/deep/ .el-table tr,
/deep/ .el-table td {
  background-color: transparent;
}
/* 头像 */
.avatar-uploader{
  margin-left: 0px;
  /* border: 1px dashed #666; */
  width: 178px;
  height: 178px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d92323;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  margin-left: 30px;
  margin-top: 20px;
  width: 100px;
  height: 100px;
  display: block;
}
/*签名  */
.jianming{
  width: 200px;
  background-color: rgb(218, 220, 232);
  border: 0;
  text-align: center;
  font-size: 15px;
  color: #060606;
  outline: none;
  border-radius: 10px;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.head-sculpture{
  margin-left: 0px;
  background: url('../../../../assets/images/userBack.jpg');
}
.userinfoName{
  margin-top: 20px;
  color: #170231;
  font-size: 40px;
  margin-left: -100px;
  font-weight: normal;
}
::v-deep .el-tabs__nav-scroll{
  margin-left: 200px;
  width: 50%;
}
.first-row{
  margin-left: 0px;
}

.like {
  cursor: pointer;
  font-size: 25px;
  display: inline-block;
}
.yue{
  font-size: 50px
}
/deep/ .el-table__header{
  background-color: transparent;
}
.el-table__header{
  background-color: transparent;
}
.el-table th.el-table__cell{
  background-color: transparent;
}
</style>
